<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\H5\ActiveController;
use App\Http\Models\Active\ActiveModel;
use App\Http\Models\Active\RankScoreModel;
use App\Http\Models\Game\RankScoreHistoryModel;
use App\Http\Models\Shop\GoodsModel;
use App\Http\Models\Shop\StoreModel;
use App\Http\Models\User\ApplyMailModel;
use App\Http\Models\User\DollModel;
use App\System\SystemSettingModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CronTabController extends Controller
{
    public function day()
    {
        $this->check_order();
    }
    public function hour()
    {
//        $this->check_stock();
        $this->save_rank_history();
    }
    /**
     *  每天0点关闭所有未支付的订单
     **/
    public function check_order(Request $request)
    {
        //获取到所有的order_sn
        $order_sn = ApplyMailModel::get_order_list(1);
        foreach ($order_sn as $value)
        {
            ApplyMailModel::cancelOrder([],$value);
        }

        return 1;
    }
    /**
     * 每小时检查库存
     */
    public function check_stock(Request $request)
    {
        $system_setting = SystemSettingModel::where('key','stock_threshold')->first()->value;
        //检查所有的doll表,如果库存不足则要通知商铺
        $shop_list = [];//待通知的商铺id列表
        foreach (DollModel::all() as $value)
        {
            if ($system_setting > $value->stock && in_array($value->store_id,$shop_list))
                $shop_list[$value->store_id] .= $value->doll_title .'、' ;
        }
        //发送短信给商铺
        foreach ($shop_list as $key => $value)
        {
            $store = StoreModel::find($key);
            CoreController::send_alert_sms($store->store_phone,$value,$system_setting);
        }

        {
            //TODO:
            //检查所有的goods表,如果库存不足要通知自己人
//            foreach (GoodsModel::all() as $value)
//            {
//
//            }
        }
    }

    /**
     *  早上10~12 12~2 2~4 4~6 6~8 清空积分缓存,并且将榜单储存到数据库中
     */
    public function save_rank_history(ActiveController $activeController)
    {
        $now = ActiveModel::select(DB::raw("* ,FROM_UNIXTIME( end_time, '%Y%m%d%H' ) as end_date "))
                ->having('end_date','=',date('YmdH'));
        if (!empty($now))
        {
            $HistoryModel                   = new RankScoreHistoryModel();
            $data                           = RankScoreModel::winnerList();
            $HistoryModel ->active_id       = $data['big'][0]['active_id'];
            $HistoryModel ->history_data    = json_encode($data);
            $HistoryModel ->save();
            RankScoreModel::query()->update(['rank_score'=>0,'big_arrival_time'=>0,'small_arrival_time'=>0,'active_id'=>0]);
        }

    }
}
